#include "DataAnalysis.h"

DataAnalysis::DataAnalysis()
{
    pState = new PCRState();
    table = new GuideTable2(this);
}
DataAnalysis::~DataAnalysis(){
    if(table){
        delete table;
        table = nullptr;
    }
}

void DataAnalysis::datao(QString outdir){
    pState->init();

    DebugLog::write("DataAnalyss line18 开始下游操作意见分析");
    DebugLog::write("DataAnalyss line18 下游意见暂时跳过");

//    table->init(pState);
//    table->hide();

    DebugLog::write("DataAnalysis line18 开始导出报告");
    if(outdir == ""){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QString sql=QString("Select Name from ItemCode Where DicCode=100");
        query.exec(sql);
        while(query.next()){
            outdir = query.value("Name").toString();
        }
    }

    qDebug() << "导出路径: " << outdir;

    execDatao(outdir);

}


QString DataAnalysis::execDatao(QString outdir)
{
#ifdef Q_OS_ANDROID
    // SMB路径处理
    QString remoteDir = outdir;
    outdir = SMBManager::SMB2Local(remoteDir);
#endif

    QDir dir;
    if (!dir.exists(outdir)) {
        dir.mkpath(outdir); // 创建目录
    }

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    // 创建xlsx文档
    QXlsx::Document xlsx;
    QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd_HH-mm-ss");
    QString outpath = outdir + "/" + currentTime + ".csv";
    QFile file(outpath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(nullptr, "Error", "Could not open file for writing:" + file.errorString());
        return "";
    }

    xlsx.addSheet("样本设置");
    xlsx.addSheet("原始数据");
    xlsx.addSheet("扩增数据");
    xlsx.addSheet("结果分析");


    xlsx.selectSheet("样本设置");       // =========================================== 样本设置
    xlsx.write(1,1,"仪器名称");
    xlsx.write(2,1,"创建日期");
    xlsx.write(3,1,"实验名称");
    xlsx.write(4,1,"实验结束时间");
    xlsx.write(1,2,"96-PCR");

    xlsx.write(6, 1, "孔位");
    xlsx.write(6, 2, "样本名称");
    xlsx.write(6, 3, "样本类型");
    xlsx.write(6, 4, "荧光染料");
    xlsx.write(6, 5, "浓度");
    int lineIdx = 7;
    foreach(PosiName posi, pState->posiList_filter){
        foreach(ChannelName channel, pState->channelList_filter){
            if(!pState->sampleInfo_posi.contains(posi)){
                continue;
            }
            xlsx.write(lineIdx, 1, pState->sampleInfo_posi[posi][0]);
            xlsx.write(lineIdx, 2, pState->sampleInfo_posi[posi][1]);
            xlsx.write(lineIdx, 3, pState->sampleInfo_posi[posi][2]);
            xlsx.write(lineIdx, 4, channel);
            xlsx.write(lineIdx, 5, pState->sampleInfo_posi[posi][3]);
            lineIdx ++;
        }

    }

    xlsx.selectSheet("原始数据");       // ============================================ 原始数据
    xlsx.write(1, 1, "孔位");
    xlsx.write(1, 2, "循环数");
    for(int i = 0; i < pState->channelList_filter.size(); i ++){
        xlsx.write(1, i+3, *(pState->channelList_filter.begin()+i));
    }

    lineIdx = 2;
    // 循环数
    for(int cycle = 1; cycle <= pState->cycleNum; cycle ++){
        // 孔位
        foreach(QString posi, pState->posiList_filter){
            xlsx.write(lineIdx, 1, posi);
            xlsx.write(lineIdx, 2, cycle);
            for(int i = 0; i < pState->channelList_filter.size(); i ++){
                QString channel = *(pState->channelList_filter.begin()+i);
                QString curveName = CurveName(channel, posi);
                if(!(pState->rawData.contains(curveName) && pState->rawData[curveName].size() > (cycle-1))){
                    continue;
                }
                double data = pState->rawData[curveName][cycle-1].y();
                xlsx.write(lineIdx, i+3, data);
            }
            lineIdx ++;
        }
    }

    xlsx.selectSheet("扩增数据");       // ============================================ 扩增数据
    xlsx.write(1, 1, "孔位");
    xlsx.write(1, 2, "循环数");
    xlsx.write(1, 3, "荧光染料");
    xlsx.write(1, 4, "Rn");
    xlsx.write(1, 5, "ΔRn");

    lineIdx = 2;
    foreach(QString channel, pState->channelList_filter){
        foreach(QString posi, pState->posiList_filter){
            QString curveName = CurveName(channel, posi);
            try {
                for(int i = 0; i < pState->modelList[curveName]->getFittedData().size(); i ++){

                    if(pState->modelList[curveName]->getFittedData()[i].x() == 0){
                        continue;
                    }

                    xlsx.write(lineIdx, 1, posi);
                    xlsx.write(lineIdx, 2, pState->modelList[curveName]->getFittedData()[i].x());
                    xlsx.write(lineIdx, 3, channel);
                    if((!pState->modelList.contains(curveName))){
                        lineIdx ++;
                        continue;
                    }
                    xlsx.write(lineIdx, 4, pState->modelList[curveName]->getFittedData()[i].y());
                    xlsx.write(lineIdx, 5, pState->modelList[curveName]->getFittedData_delta()[i].y());

                    lineIdx ++;
                }
            } catch (...) {
                qDebug("DATAO-出错line126");
            }

        }
    }
    // 循环数


    xlsx.selectSheet("结果分析");       // ============================================ 结果分析
    xlsx.write(1,1,"孔位");
    xlsx.write(1,2,"样本名称");
    xlsx.write(1,3,"样本类型");
    xlsx.write(1,4,"荧光染料");
    xlsx.write(1,5,"Ct");
    xlsx.write(1,6,"浓度");
    xlsx.write(1,7,"浓度平均值");
    xlsx.write(1,8,"y轴截距");
    xlsx.write(1,9,"斜率");
    xlsx.write(1,10,"扩增效率");
    lineIdx = 2;
    foreach(PosiName posi, pState->posiList_filter){
        foreach(ChannelName channel, pState->channelList_filter){

            CurveName name = CurveName(channel, posi);
            xlsx.write(lineIdx, 1, posi);
            if(pState->sampleInfo_posi.contains(posi))    xlsx.write(lineIdx, 2, pState->sampleInfo_posi[posi][1]);
            if(pState->sampleInfo_posi.contains(posi))    xlsx.write(lineIdx, 3, pState->sampleInfo_posi[posi][2]);
            if(pState->sampleInfo_posi.contains(posi))    xlsx.write(lineIdx, 4, channel);
            if(pState->modelList.contains(name))          xlsx.write(lineIdx, 5, pState->modelList[name]->getCt_relative());
            if(pState->concList.contains(name))           xlsx.write(lineIdx, 6, pState->concList[name]);
            if(pState->avgConcList.contains(channel))     xlsx.write(lineIdx, 7, pState->avgConcList[channel]);
            if(pState->standardLine.contains(channel))    xlsx.write(lineIdx, 8, pState->standardLine[channel][1]);
            if(pState->modelList.contains(name))          xlsx.write(lineIdx, 9, pState->modelList[name]->getSlope());
            if(pState->modelList.contains(name))          xlsx.write(lineIdx, 10, pState->modelList[name]->getEfficiency());
            lineIdx ++;
        }
    }

    // 关闭文件
    if(xlsx.saveAs(outpath)){
        qDebug("导出成功");
    }else{
        qDebug("导出失败");
    }

     // table->save(outpath);



#ifdef Q_OS_ANDROID
    if(SMBManager::isSMBPath(remoteDir)){
        bool res = SMBManager::I().uploadFile(remoteDir + outpath.split("/").back(), outpath);
        if(res){
            qDebug("上传成功");
        }else{
            qDebug("上传失败");
        }
    }
#endif
    file.close();

    return outpath;

}
